local constrained_size = require 'constrained_size'
local single_child_view = require "views.single_child_view"
local vec2 = require "vec2"
local math_extended = require "math_extended"

---@class sized_box: single_child_view
---@field width number?
---@field height number?
---@field child view
local sized_box = single_child_view:new_view_type()

---@class sized_box.renderer_type: single_child_view.renderer
---@field child_renderer view.renderer
sized_box.renderer = single_child_view.renderer:new_renderer_type()

---@param options { width: number?, height: number?, child: view }
function sized_box:__call(options)
    self:set_view_prototype(options)

    assert(options.child)

    return options
end

---@param constraints constraints
---@param v sized_box
function sized_box.renderer:layout(constraints, v)
    return constrained_size(
        v.width ~= nil
            and math_extended.clamp(v.width, constraints.min_size.x, constraints.max_size.x)
            or nil,
        v.height ~= nil
            and math_extended.clamp(v.height, constraints.min_size.y, constraints.max_size.y)
            or nil
    )
end

---@param render_rect rect
---@param view sized_box
function sized_box.renderer:render(render_rect, view)
    local render_rect = render_rect:copy()
    local size = constrained_size(view.width, view.height):to_vec2_or(render_rect:size())
    render_rect.extents = render_rect.extents:clamp(vec2(0), size * 0.5)
    self.child_renderer:render(render_rect, view.child)
end

return sized_box
